package com.xiashuxia.orgims.dao;

import java.util.List;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.xiashuxia.orgims.model.User;


@Repository
public class UserDAO {
	
	@Resource(name="orgimsSessionFactory")
    private SessionFactory sessionFactory;

	public Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	@Transactional
	public void createUser(User user) {
		Session session = getSession();
		session.save(user);

		session.flush();
	}

	@Transactional
	public User getUserByUID(long UID) {
		Session session = getSession();

		@SuppressWarnings("unchecked")
		List<User> users = (List<User>) session
				.createQuery("from User where UID = ?0").setLong("0", UID)
				.list();
		for (User user : users) {
			if (user.getUID() == UID) {
				return user;
			}
		}

		return null;
	}

	@Transactional
	public User getUserByUsername(String username) {
		Session session = getSession();

		System.out.println("session null?" + (session == null));

		@SuppressWarnings("unchecked")
		List<User> users = (List<User>) session
				.createQuery("FROM User WHERE username = ?0")
				.setString("0", username).list();

		for (User user : users) {
			if (user.getUsername().equals(username)) {
				return user;
			}
		}

		return null;
	}
}